/*
 * Copyright 2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * AbstractConfigMapper.java | Created on Apr 22, 2010
 */
package org.gp.gpetl.mapper;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.gp.gpetl.config.ConfigObject;
import org.gp.gpetl.exception.MappingException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

/**
 * Abstract class for a file mapper
 *
 * @author Paul Augustine C. Mendoza
 * @since 1.0
 */
public abstract class AbstractConfigMapper implements ConfigMapper {

    /**
     * The mapping rules identifier
     */
    private static final String RULES_FILE = "mapping-rules.xml";

    /**
     * Default mapping file identifier
     */
    private static final String DEFAULT_MAPPING_FILE = "mapping.xml";

    /**
     * The path of the mapping file
     */
    private String mappingFilePath;

    /**
     * Initializes the audit configurations
     *
     * @throws MappingException if mapping from file fails
     */
    protected void initializeConfig() throws MappingException {
        URL url = this.getClass().getClassLoader().getResource(RULES_FILE);
        String mappingRulesPath = url.getPath();
        StringBuffer msg = new StringBuffer();
        if (!hasValidParameters(msg)) {
            throw new IllegalArgumentException(
                    "Invalid mapping configuration parameters: " + msg);
        }
        try {
            // Create the digester
            Digester digester = DigesterLoader
                    .createDigester(new InputSource(
                            new FileInputStream(
                                    new File(mappingRulesPath))));
            // Parse the configuration file
            ConfigObject configObject = (ConfigObject) digester
                    .parse(new File(this.mappingFilePath));
            if (configObject == null) {
                throw new MappingException("Config object is null.", this);
            }
            processConfigObject(configObject);
        } catch (SAXException e) {
            throw new MappingException(e, this);
        } catch (IOException e) {
            throw new MappingException(e, this);
        }
    }

    /**
     * Checks if the parameters are valid
     *
     * @param msg error message
     * @return true if valid
     */
    private boolean hasValidParameters(StringBuffer msg) {
        if (this.mappingFilePath == null) {
            msg.append("Mapping file path is null.");
            return false;
        }
        if (StringUtils.isBlank(this.mappingFilePath)) {
            // If this is blank, assume current path
            URL url = this.getClass().getClassLoader().getResource(".");
            File defaultMapping =
                    new File(FileUtils.toFile(url), DEFAULT_MAPPING_FILE);
            this.mappingFilePath = defaultMapping.getPath();            
        }
        if (!new File(this.mappingFilePath).exists()) {
            msg.append("Mapping file " + this.mappingFilePath + " does not exist");
            return false;
        }
        return true;
    }

    /**
     * Maps the file to a bean
     *
     * @param configObject the configuration object
     */
    protected abstract void processConfigObject(ConfigObject configObject);

    /**
     * @see org.gp.gpetl.mapper.ConfigMapper#setMappingFilePath(String)
     */
    public void setMappingFilePath(String mappingFilePath) {
        this.mappingFilePath = mappingFilePath;
    }

}
